package com.example.myapplication;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ViewConfiguration;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

public class ViewPagerSwipeRefreshLayout extends SwipeRefreshLayout {

    float downX;
    float downY;

    private boolean isVPDrag = false;

    private int touchSlop;

    private static final String TAG = "ViewPagerSwipeRefreshLa";

    public ViewPagerSwipeRefreshLayout(@NonNull Context context) {
        super(context);
    }

    public ViewPagerSwipeRefreshLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    // 外部拦截法

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = ev.getX();
                downY = (int) ev.getY();
                isVPDrag = false;
                break;
            case MotionEvent.ACTION_MOVE:
                if (isVPDrag) {
                    return false;
                }
                float dx = Math.abs(ev.getX() - downX);
                float dy = Math.abs(ev.getY() - downY);
                // 方式1.通过位移判断
               /* if (dx > dy) {
                    // 如果x方向的位移大于y方向，说明是横向滑动，不拦截事件
                    return false;
                }*/
                // 方式2.通过角度判断
                double radians = Math.atan2(dy, dx);
                double degrees = Math.toDegrees(radians);
                Log.d(TAG, "onInterceptTouchEvent: " + degrees);
                if (dx>touchSlop&&degrees < 45) {
                    isVPDrag = true;
                    return false;
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                isVPDrag = false;
        }
        return super.onInterceptTouchEvent(ev);
    }
}
